﻿using AutoMapper;
using KayakMes.Common;
using KayakMes.Common.Dtos.WarehouseManageDto.Input;
using KayakMes.Common.Dtos.WarehouseManageDto.Output;
using KayakMes.Common.Result;
using KayakMes.WarehouseManage.Domain.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace KayakMes.WarehouseManage.Application
{
    /// <summary>
    /// 仓库管理服务实现类
    /// 实现采购订单相关的业务逻辑操作
    /// </summary>
    public class WarehouseManageServices : IWarehouseManageServices
    {
        private static readonly object _Lock = new object();
        /// <summary>
        /// 采购订单仓储接口
        /// </summary>
        private readonly BaseReposiotry<PurchaseOrderModel> purchaseorderRepository;
        private readonly BaseReposiotry<WarehouseModel> warehouseRepository;
        private readonly BaseReposiotry<WarehouseAreaModel> warehouseareaRepository;

        /// <summary>
        /// 构造函数，依赖注入采购订单仓储
        /// </summary>
        /// <param name="purchaseorderRepository">采购订单仓储实例</param>
        public WarehouseManageServices(BaseReposiotry<PurchaseOrderModel> purchaseorderRepository,BaseReposiotry<WarehouseModel> warehouseRepository,BaseReposiotry<WarehouseAreaModel> warehouseareaRepository)
        {
            this.purchaseorderRepository = purchaseorderRepository;
            this.warehouseRepository = warehouseRepository;
            this.warehouseareaRepository = warehouseareaRepository;
        }
        #region 采购订单接口实现

        /// <summary>
        /// 添加采购订单
        /// </summary>
        /// <param name="purchaseOrderModel">采购订单模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> AddPurchaseOrder(PurchaseOrderModel purchaseOrderModel)
        {
            purchaseOrderModel.Id=YitIdHelper.NextId(); // 生成唯一ID
            var res = purchaseorderRepository.Insert(purchaseOrderModel);
            if (res)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "添加成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "添加失败", Data = 0 };
            }
        }

        /// <summary>
        /// 获取采购订单列表（支持分页查询）
        /// </summary>
        /// <param name="dto">采购订单查询条件DTO</param>
        /// <returns>返回分页的采购订单列表</returns>
        public ApiPaging<PurchaseOrderModel> GetAllPurchaseOrders(PurchaseOrderDto dto)
        {
            var res = purchaseorderRepository.GetAll().Where(x=>!x.IsDeleted);
            ApiPaging<PurchaseOrderModel> apiPaging = new ApiPaging<PurchaseOrderModel>
            {
                Total = res.Count(),
                PageIndex = dto.Index,
                PageSize = dto.Size,
                Items = res.Skip((dto.Index - 1) * dto.Size).Take(dto.Size).ToList()
            };
            return apiPaging;
        }

        /// <summary>
        /// 根据ID获取指定的采购订单
        /// </summary>
        /// <param name="id">采购订单ID</param>
        /// <returns>返回操作结果，包含指定的采购订单信息</returns>
        public ApiResult<PurchaseOrderModel> GetPurchaseOrder(long id)
        {
            var purchaseOrder = purchaseorderRepository.GetModel(id);
            if (purchaseOrder == null)
            {
                return new ApiResult<PurchaseOrderModel> { Code = ApiEnums.NotFound, Message = "订单未找到", Data = null };
            }
            if (purchaseOrder.IsDeleted == true)
            {
                return new ApiResult<PurchaseOrderModel> { Code = ApiEnums.NotFound, Message = "订单已被删除", Data = null };
            }
            return new ApiResult<PurchaseOrderModel> { Code = ApiEnums.Success, Message = "订单查询成功", Data = purchaseOrder };
        }

        /// <summary>
        /// 更新采购订单信息
        /// </summary>
        /// <param name="purchaseOrderModel">采购订单模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> UpdatePurchaseOrder(PurchaseOrderModel purchaseOrderModel)
        {
            var res = purchaseorderRepository.Update(purchaseOrderModel);
            if (res > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "更新成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "更新失败", Data = 0 };
            }
        }

        /// <summary>
        /// 逻辑删除采购订单
        /// 将订单的IsDeleted字段设置为true，而不是物理删除
        /// </summary>
        /// <param name="Id">采购订单ID</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> LogicDel(long Id)
        {
            var res = purchaseorderRepository.GetModel(Id);
            if (res == null || res.IsDeleted == true)
            {
                return new ApiResult<int> { Code = ApiEnums.NotFound, Message = "订单未找到或已被删除", Data = 0 };
            }
            res.IsDeleted = true;
            var updateResult = purchaseorderRepository.Update(res);
            if (updateResult > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "订单删除成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "订单删除失败", Data = 0 };
            }
        }

        /// <summary>
        /// 随机生成检测项目编号
        /// </summary>
        /// <returns>格式为 PC001 的字符串</returns>
        public string GetCode()
        {
            string todayPrefix = "RE" + DateTime.Now.ToString("yyyyMMdd");

            // 只查找今天的编号
            //var todayCodes = purchaseorderRepository.GetAll()
            //    .Where(x => x.OrderNumber != null && x.OrderNumber != "" && SqlFunc.StartsWith(x.OrderNumber, todayPrefix))
            //    .Select(x => x.OrderNumber)
            //    .ToList();
            var todayCodes = purchaseorderRepository.GetAll()
                            .Where(x => x.OrderNumber.Contains(todayPrefix))
                            .Select(x => x.OrderNumber)
                            .ToList();
            int nextNumber = 1;

            if (todayCodes.Any())
            {
                // 取最大流水号
                var maxCode = todayCodes
                    .OrderByDescending(x => x)
                    .First();

                // 截取后三位流水号
                var numPart = maxCode.Substring(todayPrefix.Length);
                if (int.TryParse(numPart, out int currentNum))
                {
                    nextNumber = currentNum + 1;
                }
            }

            return $"{todayPrefix}{nextNumber:D3}";
        }
        #endregion

        #region 仓库接口实现
        /// <summary>
        /// 添加仓库
        /// </summary>
        /// <param name="purchaseOrderModel">仓库模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> AddWarehouse(WarehouseAddDto warehouseModel)
        {
            WarehouseModel model= new WarehouseModel
            {
                WarehouseCode = warehouseModel.WarehouseCode,
                WarehouseName = warehouseModel.WarehouseName,
                WarehouseAddress = warehouseModel.WarehouseAddress,
                WarehouseArea = warehouseModel.WarehouseArea,
                ResponsiblePerson=warehouseModel.ResponsiblePerson,
                Id=YitIdHelper.NextId(),
                Remark= warehouseModel.Remark,
                CreateUserId= "amdin",
                IsDeleted = false,
                CreateTime = DateTime.Now
            };
            model.Id=YitIdHelper.NextId();
            var res = warehouseRepository.Insert(model);
            if (res)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "添加成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "添加失败", Data = 0 };
            }
        }
        /// <summary>
        /// 更新仓库信息
        /// </summary>
        /// <param name="purchaseOrderModel">仓库模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> UpdateWarehouse(WarehouseModel warehouseModel)
        {
            var res = warehouseRepository.Update(warehouseModel);
            if (res > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "更新成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "更新失败", Data = 0 };
            }
        }
        /// <summary>
        /// 逻辑删除仓库
        /// 将仓库的IsDeleted字段设置为true，而不是物理删除
        /// </summary>
        /// <param name="Id">仓库ID</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> LogicDelWarehouse(long Id)
        {
            var res = warehouseRepository.GetModel(Id);
            if (res == null || res.IsDeleted == true)
            {
                return new ApiResult<int> { Code = ApiEnums.NotFound, Message = "仓库不存在或已被移除", Data = 0 };
            }
            res.IsDeleted = true;
            var updateResult = warehouseRepository.Update(res);
            if (updateResult > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "仓库移除成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "仓库移除失败", Data = 0 };
            }
        }
        /// <summary>
        /// 获取仓库列表（支持分页查询）
        /// </summary>
        /// <param name="dto">仓库列表查询条件DTO</param>
        /// <returns>返回分页的仓库列表</returns>
        public ApiPaging<WarehouseModel> GetAllWarehouse(WarehouseDto dto)
        {
            ApiPaging<WarehouseModel> apiPaging = new ApiPaging<WarehouseModel>();
            var res = warehouseRepository.GetAll().Where(x=>!x.IsDeleted);
            if (res.Count() > 0) 
            {
                if (!string.IsNullOrEmpty(dto.WarehouseCode))
                {
                    res = res.Where(x => x.WarehouseCode.Contains(dto.WarehouseCode));
                }
                if (!string.IsNullOrEmpty(dto.WarehouseName))
                {
                    res = res.Where(x => x.WarehouseName.Contains(dto.WarehouseName));
                }
                apiPaging.Total = res.Count();
                apiPaging.PageIndex = dto.Index;
                apiPaging.PageSize = dto.Size;
                apiPaging.Items = res.Skip((dto.Index - 1) * dto.Size).Take(dto.Size).ToList();
                return apiPaging;
            }
            apiPaging.Total = res.Count();
            apiPaging.PageIndex = dto.Index;
            apiPaging.PageSize = dto.Size;
            apiPaging.Message = "未查到仓库数据";
            return apiPaging;
        }
        /// <summary>
        /// 根据ID查询指定的仓库
        /// </summary>
        /// <param name="id">采仓库ID</param>
        /// <returns>返回操作结果，包含指定的仓库信息</returns>
        public ApiResult<WarehouseModel> GetWarehouse(long Id)
        {
            var warehouse = warehouseRepository.GetModel(Id);
            if (warehouse == null|| warehouse.IsDeleted == true)
            {
                return new ApiResult<WarehouseModel> { Code = ApiEnums.NotFound, Message = "仓库未找到或被移除", Data = null };
            }
            return new ApiResult<WarehouseModel> { Code = ApiEnums.Success, Message = "仓库查询成功", Data = warehouse };
        }
        /// <summary>
        /// 随机生成仓库编号
        /// </summary>
        /// <returns>字符串</returns>
        public string GetWarehouseCode()
        {
            string todayPrefix = "WH" + DateTime.Now.ToString("yyyyMMdd");
            // 只查找今天的编号
            var todayCodes = warehouseRepository.GetAll()
                            .Where(x => x.WarehouseCode.Contains(todayPrefix))
                            .Select(x => x.WarehouseCode)
                            .ToList();

            int nextNumber = 1;

            if (todayCodes.Any())
            {
                // 取最大流水号
                var maxCode = todayCodes
                    .OrderByDescending(x => x)
                    .First();

                // 截取后三位流水号
                var numPart = maxCode.Substring(todayPrefix.Length);
                if (int.TryParse(numPart, out int currentNum))
                {
                    nextNumber = currentNum + 1;
                }
            }

            return $"{todayPrefix}{nextNumber:D3}";
        }
        /// <summary>
        /// 仓库的下拉框数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<List<WarehouseOutput>> ComboBoxWarehouse()
        {
            var warehouses = warehouseRepository.GetAll().Where(x => !x.IsDeleted).ToList();
            if (warehouses == null || warehouses.Count == 0)
            {
                return new ApiResult<List<WarehouseOutput>> { Code = ApiEnums.NotFound, Message = "未找到仓库数据", Data = null };
            }
            List<WarehouseOutput> res = new List<WarehouseOutput>();
            foreach (var item in warehouses)
            {
                res.Add(new WarehouseOutput
                {
                    Id = item.Id,
                    WarehouseName = item.WarehouseName
                });
            }
            return new ApiResult<List<WarehouseOutput>> { Code = ApiEnums.Success, Message = "仓库查询成功", Data = res };
        }
        #endregion
        #region 库区接口实现
        /// <summary>
        /// 添加库区
        /// </summary>
        /// <param name="purchaseOrderModel">库区模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> AddWarehouseArea(WarehouseAreaAddDto dto)
        {
            WarehouseAreaModel model = new WarehouseAreaModel
            {
                WarehouseAreaCode = dto.WarehouseAreaCode,
                WarehouseAreaName = dto.WarehouseAreaName,
                WarehouseAreaAddress = dto.WarehouseAreaAddress,
                Area = dto.Area,
                Principal = dto.Principal,
                Remark = dto.Remark,
                WarehouseId=dto.WarehouseId,
                Id = YitIdHelper.NextId(),
                CreateUserId = "amdin",
                IsDeleted = false,
                CreateTime = DateTime.Now
            };
            var res = warehouseareaRepository.Insert(model);
            if (res)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "添加成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "添加失败", Data = 0 };
            }
        }

        /// <summary>
        /// 更新库区信息
        /// </summary>
        /// <param name="purchaseOrderModel">库区模型</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> UpdateWarehouseArea(WarehouseAreaModel model)
        {
            var res = warehouseareaRepository.Update(model);
            if (res > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "更新成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "更新失败", Data = 0 };
            }
        }

        /// <summary>
        /// 逻辑删除库区
        /// 将库区的IsDeleted字段设置为true，而不是物理删除
        /// </summary>
        /// <param name="Id">库区ID</param>
        /// <returns>返回操作结果，成功返回1，失败返回0</returns>
        public ApiResult<int> LogicDelWarehouseArea(long Id)
        {
            var res = warehouseareaRepository.GetModel(Id);
            if (res == null || res.IsDeleted == true)
            {
                return new ApiResult<int> { Code = ApiEnums.NotFound, Message = "库区不存在或已被移除", Data = 0 };
            }
            res.IsDeleted = true;
            var updateResult = warehouseareaRepository.Update(res);
            if (updateResult > 0)
            {
                return new ApiResult<int> { Code = ApiEnums.Success, Message = "库区移除成功", Data = 1 };
            }
            else
            {
                return new ApiResult<int> { Code = ApiEnums.Fail, Message = "库区移除失败", Data = 0 };
            }
        }

        /// <summary>
        /// 获取库区列表（支持分页查询）
        /// </summary>
        /// <param name="dto">库区列表查询条件DTO</param>
        /// <returns>返回分页的库区列表</returns>
        public ApiPaging<WarehouseAreaOutput> GetAllWarehouseArea(WarehouseAreaDto dto)
        {
            ApiPaging<WarehouseAreaOutput> apiPaging = new ApiPaging<WarehouseAreaOutput>();
            var res = warehouseareaRepository.GetAll().Where(x => !x.IsDeleted);

            if (res.Count() > 0)
            {
                if (!string.IsNullOrEmpty(dto.WarehouseAreaCode))
                {
                    res = res.Where(x => x.WarehouseAreaCode.Contains(dto.WarehouseAreaCode));
                }
                if (!string.IsNullOrEmpty(dto.WarehouseAreaName))
                {
                    res = res.Where(x => x.WarehouseAreaName.Contains(dto.WarehouseAreaName));
                }
                List<WarehouseAreaOutput> warehouseAreaOutputs = new List<WarehouseAreaOutput>();
                foreach (var item in res.ToList())
                {
                    warehouseAreaOutputs.Add(new WarehouseAreaOutput
                    {
                        WarehouseAreaCode = item.WarehouseAreaCode,
                        WarehouseAreaName = item.WarehouseAreaName,
                        WarehouseAreaAddress = item.WarehouseAreaAddress,
                        Area = item.Area,
                        Principal = item.Principal,
                        Remark = item.Remark,
                        WarehouseName = warehouseRepository.GetModel(item.WarehouseId).WarehouseName
                    });
                }
                apiPaging.Total = res.Count();
                apiPaging.PageIndex = dto.Index;
                apiPaging.PageSize = dto.Size;
                apiPaging.Items = warehouseAreaOutputs.Skip((dto.Index - 1) * dto.Size).Take(dto.Size).ToList();
                return apiPaging;
            }
            else 
            {
                apiPaging.Total = res.Count();
                apiPaging.PageIndex = dto.Index;
                apiPaging.PageSize = dto.Size;
                apiPaging.Message = "未查到库区数据";
                return apiPaging;
            }
        
        }

        /// <summary>
        /// 根据ID查询指定的库区
        /// </summary>
        /// <param name="id">库区ID</param>
        /// <returns>返回操作结果，包含指定的库区信息</returns>
        public ApiResult<WarehouseAreaModel> GetWarehouseArea(long Id)
        {
            var warehousearea = warehouseareaRepository.GetModel(Id);
            if (warehousearea == null || warehousearea.IsDeleted == true)
            {
                return new ApiResult<WarehouseAreaModel> { Code = ApiEnums.NotFound, Message = "库区未找到或被移除", Data = null };
            }
            return new ApiResult<WarehouseAreaModel> { Code = ApiEnums.Success, Message = "库区查询成功", Data = warehousearea };
        }

        /// <summary>
        /// 随机生成库区编号
        /// </summary>
        /// <returns>字符串</returns>
        public string GetWarehouseAreaCode()
        {
            string todayPrefix = "WA" + DateTime.Now.ToString("yyyyMMdd");
            // 只查找今天的编号
            var todayCodes = warehouseareaRepository.GetAll()
                            .Where(x => x.WarehouseAreaCode.Contains(todayPrefix))
                            .Select(x => x.WarehouseAreaCode)
                            .ToList();

            int nextNumber = 1;

            if (todayCodes.Any())
            {
                // 取最大流水号
                var maxCode = todayCodes
                    .OrderByDescending(x => x)
                    .First();

                // 截取后三位流水号
                var numPart = maxCode.Substring(todayPrefix.Length);
                if (int.TryParse(numPart, out int currentNum))
                {
                    nextNumber = currentNum + 1;
                }
            }

            return $"{todayPrefix}{nextNumber:D3}";
        }
        #endregion
    }
}
